/**  定义Admin相关的接口 */
const express = require("express");
const router = express.Router();
const Response = require("../utils/Response.js");
const md5pwd=require('../utils/md5password.js')

// 引入mysql连接池
const pool = require("../utils/db.js");

const jwt = require("jsonwebtoken");
const SECRET_KEY = "JWT_SECRET_KEY";

/**
 * 处理登录业务
 */
// 用户登录
router.post("/user/login", (req, resp) => {
  let { user_phone, user_pwd } = req.body;
  // 表单验证  后端验证
  // let schema = Joi.object({
  //   username: Joi.string().required().pattern(new RegExp('^\\w{3,15}$')), // 必填
  //   password: Joi.string().required().pattern(new RegExp('^\\w{6,15}$')), // 必填
  // });
  // let { error, value } = schema.validate(req.body);
  // if (error) {
  //   resp.send(Response.error(400, error));
  //   return; // 结束
  // }
  // 查询数据库，账号密码是否填写正确
  let sql = "select * from user_b where user_phone=? and user_pwd=MD5(?)";
  pool.query(sql, [user_phone, user_pwd], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length == 0) {
      // console.log();
      resp.send(Response.error(1001, "账号密码输入错误"));
    } else {
      // 获取登录用户对象
      let user = result[0];
      // 为该用户颁发一个token字符串，未来该客户端若做发送其他请求，则需要在请求Header中携带token，完成状态管理。
      // 定制存入token的数据
      let payload = { id: user.user_id, phone: user.user_phone };
      let token = jwt.sign(payload, SECRET_KEY, { expiresIn: "1d" });
      // 返回user对象与token字符串
      user.password = undefined;
      resp.send(Response.ok({ user, token }));
    }
  });
});
// 管理员手机查重
router.get("/user1/phone", (req, resp) => {
  let { user_phone } = req.query;
  let sql = "select * from user_a where user_phone=?";
  pool.query(sql, [user_phone], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length == 0) {
      // console.log();
      resp.send(Response.ok());
    } else {
      resp.send(Response.error(300,"手机号重复"));
    }
  });
});

// 用户手机查重
router.get("/user/phone", (req, resp) => {
  let { user_phone } = req.query;
  let sql = "select * from user_b where user_phone=?";
  pool.query(sql, [user_phone], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length == 0) {
      // console.log();
      resp.send(Response.ok());
    } else {
      resp.send(Response.error(300,"手机号重复"));
    }
  });
});
// 管理员登录
router.post("/user1/login", (req, resp) => {
  let { user_phone, user_pwd } = req.body;
  let sql = "select * from user_a where user_phone=? and user_pwd=MD5(?)";
  pool.query(sql, [user_phone, user_pwd], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length == 0) {
      // console.log();
      resp.send(Response.error(1001, "账号密码输入错误"));
    } else {
      // 获取登录用户对象
      let user = result[0];
      // 为该用户颁发一个token字符串，未来该客户端若做发送其他请求，则需要在请求Header中携带token，完成状态管理。
      // 定制存入token的数据
      let payload = { id: user.user_id, phone: user.user_phone };
      let token = jwt.sign(payload, SECRET_KEY, { expiresIn: "1d" });
      // 返回user对象与token字符串
      user.password = undefined;
      resp.send(Response.ok({ user, token }));
    }
  });
});
// 注册管理员
router.post("/user1/register", (req, resp) => {
  let obj = req.body;
  if (obj.user_pwd) {
    obj.user_pwd = md5pwd(obj.user_pwd)
  } else {
    obj.user_pwd = md5pwd("123456")
  }
  obj.user_name=obj.user_name?obj.user_name:obj.user_phone
  console.log(obj);
  let sql = "insert into user_a set ?";
  pool.query(sql, [obj], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 注册成功
    resp.send(Response.ok());
  });
});

// 注册用户
router.post("/user/register", (req, resp) => {
  let obj = req.body;
  if (obj.user_pwd) {
    obj.user_pwd = md5pwd(obj.user_pwd)
  } else {
    obj.user_pwd = md5pwd("123456")
  }
  obj.user_name=obj.user_name?obj.user_name:obj.user_phone
  let sql = "insert into user_b set ?";
  pool.query(sql, [obj], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 注册成功
    resp.send(Response.ok());
  });
});

// 查询用户列表 分页
router.get("/user/list", async (req, resp) => {
  let { page, pagesize } = req.query;
  let startIndex = (page - 1) * pagesize;
  let size = parseInt(pagesize);
  try {
    let sql = "select * from user_b limit ?,?";
    let result = await pool.querySync(sql, [startIndex, size]);
    let sql2 = "select count(*) as total from user_b";
    let result2 = await pool.querySync(sql2);
    // 用户列表屏蔽密码
    result.forEach((item) => {
      item.user_pwd = null;
    });
    resp.send(
      Response.ok({
        result,
        total: result2[0].total,
        pageIndex: page,
        pageSize: pagesize,
      })
    );
  } catch (error) {
    resp.send(Response.error(error));
  }
});

// 查询管理员列表 分页
router.get("/user1/list", async (req, resp) => {
  let { page, pagesize } = req.query;
  let startIndex = (page - 1) * pagesize;
  let size = parseInt(pagesize);
  try {
    let sql = "select * from user_a limit ?,?";
    let result = await pool.querySync(sql, [startIndex, size]);
    let sql2 = "select count(*) as total from user_a";
    let result2 = await pool.querySync(sql2);
    // 用户列表屏蔽密码
    result.forEach((item) => {
      item.user_pwd = null;
    });
    resp.send(
      Response.ok({
        result,
        total: result2[0].total,
        pageIndex: page,
        pageSize: pagesize,
      })
    );
  } catch (error) {
    resp.send(Response.error(error));
  }
});

// 模糊查询用户列表
router.get("/user/ByNamePhone", async (req, resp) => {
  let { page, pagesize, phonename } = req.query;
  let startIndex = (page - 1) * pagesize;
  let size = parseInt(pagesize);
  try {
    let sql = `select * from user_b where user_name like '%${phonename}%' or user_phone like '%${phonename}%' limit ?,?`;
    let result = await pool.querySync(sql, [startIndex, size]);
    let sql2 =
      `select count(*) as total from user_b where user_name like '%${phonename}%' or user_phone like '%${phonename}%'`;
    let result2 = await pool.querySync(sql2);
    // 用户列表屏蔽密码
    result.forEach((item) => {
      item.user_pwd = null;
    });
    resp.send(
      Response.ok({
        result,
        total: result2[0].total,
        pageIndex: page,
        pageSize: pagesize,
      })
    );
  } catch (error) {
    resp.send(Response.error(error));
  }
});

// 模糊查询管理员列表
router.get("/user1/ByNamePhone", async (req, resp) => {
  let { page, pagesize, phonename } = req.query;
  let startIndex = (page - 1) * pagesize;
  let size = parseInt(pagesize);
  try {
    let sql = `select * from user_a where user_name like '%${phonename}%' or user_phone like '%${phonename}%' limit ?,?`;
    let result = await pool.querySync(sql, [startIndex, size]);
    let sql2 =
      `select count(*) as total from user_a where user_name like '%${phonename}%' or user_phone like '%${phonename}%'`;
    let result2 = await pool.querySync(sql2);
    // 用户列表屏蔽密码
    result.forEach((item) => {
      item.user_pwd = null;
    });
    resp.send(
      Response.ok({
        result,
        total: result2[0].total,
        pageIndex: page,
        pageSize: pagesize,
      })
    );
  } catch (error) {
    resp.send(Response.error(error));
  }
});

// 通过id查询管理员信息
router.get("/user1/ById", (req, resp) => {
  let { user_id } = req.query;
  let sql = "select * from user_a where user_id=?";
  pool.query(sql, [user_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
      // console.log();
     resp.send(Response.ok({result}));
  });
});

// 修改管理员信息
router.post("/user1/update", (req, resp) => {
  let obj = req.body;
  let sql = "update user_a set ? where user_id=?";
  pool.query(sql, [obj, obj.user_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 修改成功
    resp.send(Response.ok());
  });
});

// 通过id查询用户信息
router.get("/user/ById", (req, resp) => {
  let { user_id } = req.query;
  let sql = "select * from user_b where user_id=?";
  pool.query(sql, [user_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
      // console.log();
     resp.send(Response.ok({result}));
  });
});

// 修改用户信息
router.post("/user/update", (req, resp) => {
  let obj = req.body;
  let sql = "update user_b set ? where user_id=?";
  pool.query(sql, [obj, obj.user_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 修改成功
    resp.send(Response.ok());
  });
});

// 修改管理员密码
router.post("/user1/updatepwd", (req, resp) => {
  let obj = req.body;
  obj.user_pwd = md5pwd(obj.user_pwd)
  let sql = "update user_a set ? where user_id=?";
  pool.query(sql, [obj, obj.user_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 修改成功
    resp.send(Response.ok());
  });
});

// 修改用户密码
router.post("/user/updatepwd", (req, resp) => {
  let obj = req.body;
  obj.user_pwd = md5pwd(obj.user_pwd)
  let sql = "update user_b set ? where user_id=?";
  pool.query(sql, [obj, obj.user_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 修改成功
    resp.send(Response.ok());
  });
});

// 查询用户列表
// router.get("/user/list", (req, resp)=>{
//   let { page, pagesize } = req.query;
//   let startIndex = (page - 1) * pagesize;
//   let size = parseInt(pagesize);
//   let sql = "select * from user_b limit ?,?"
//   pool.query(sql, [startIndex,size], (error, result)=>{
//     if (error) {
//       resp.send(Response.error(500, error));
//       throw error;
//     }
//     // 注册成功
//     resp.send(Response.ok({result}));
//   })
// });

// 删除管理员信息
router.get("/user1/del", (req, resp) => {
  let obj = req.query;
  let sql = "delete from user_a where user_id=?";
  pool.query(sql, [obj.user_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.affectedRows === 0) {
      resp.send(Response.error(400, '删除失败'))
    } else {
      // 删除成功
      resp.send(Response.ok());
    }

  });
});

// 删除用户信息
router.get("/user/del", (req, resp) => {
  let obj = req.query;
  let sql = "delete from user_b where user_id=?";
  pool.query(sql, [obj.user_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.affectedRows === 0) {
      resp.send(Response.error(400, '删除失败'))
    } else {
      // 删除成功
      resp.send(Response.ok());
    }

  });
});
// 查询角色类型
router.get("/user/usertype", (req, resp) => {
  let obj = req.query;
  let sql = "select * from role";
  pool.query(sql, [], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 删除成功
    resp.send(Response.ok({result}));
    

  });
});


// 查询所有城市
router.get("/user/city", (req, resp) => {
  let obj = req.query;
  let sql = "select * from city";
  pool.query(sql, [], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 删除成功
    resp.send(Response.ok({result}));
    

  });
});
// 将router对象导出
module.exports = router;
